﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace SSOCommon
{
    public class EncryptionManager
    {
        private const string KEY = "oYlvjlFqiyE6p4LPOioN30Yuz84AV+yn3YGNSdJKrJE=";
        private const string IV = "rJSGh2iibel6uoRkCiT0og==";

        private static byte[] KeyBytes
        {
            get
            {
                return Convert.FromBase64String(KEY);
            }
        }

        private static byte[] IVBytes
        {
            get
            {
                return Convert.FromBase64String(IV);
            }
        }

        public static string Encrypt(string message)
        {
            string returnValue = String.Empty;
            byte[] bytesEncrypt = EncryptStringToBytes(message);
            return Convert.ToBase64String(bytesEncrypt);
        }

        private static byte[] EncryptStringToBytes(string message)
        {
            byte[] bEncrypts = null;
            using (Rijndael rij = Rijndael.Create())
            {
                rij.Key = KeyBytes;
                rij.IV = IVBytes;
                ICryptoTransform encryptor = rij.CreateEncryptor(rij.Key, rij.IV);
                using (MemoryStream msStream = new MemoryStream())
                {
                    using (CryptoStream csStream = new CryptoStream(msStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter writer = new StreamWriter(csStream))
                        {
                            writer.Write(message);
                        }
                        bEncrypts = msStream.ToArray();
                    }
                }
            }
            return bEncrypts;
        }

        public static string Decrypt(string message)
        {
            byte[] bDecrypts = Convert.FromBase64String(message);
            string returnValue = null;
            using (Rijndael rij = Rijndael.Create())
            {
                rij.Key = KeyBytes;
                rij.IV = IVBytes;
                ICryptoTransform decryptor = rij.CreateDecryptor(rij.Key, rij.IV);
                
                using (MemoryStream msStream = new MemoryStream(bDecrypts))
                {
                    using (CryptoStream csStream = new CryptoStream(msStream, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(csStream))
                        {
                            returnValue = reader.ReadToEnd();
                        }
                    }
                }
            }
            return returnValue;
        }
    }
}
